/*
 * Copyright:  2018 smarabbit studio.
 *
 *  Licensed under the Confluent Community License; you may not use this file
 *  except in compliance with the License.  You may obtain a copy of the License at
 *
 *  http://www.confluent.io/confluent-community-license
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 *  WARRANTIES OF ANY KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations under the License.
 *
 *  @作   者： 黄开晖 (117227773@qq.com)
 *  @日   期:  2021年6月12日
 */
package com.massyframework.beanskin.graphql.servlet.provider;

import java.util.Objects;

import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContextAttributeListener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.websocket.server.ServerContainer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.massyframework.beanskin.graphql.servlet.GraphQLModularSchemalBuilder;

import graphql.kickstart.servlet.GraphQLWebsocketServlet;

/**
 * WebSocket 容器启动监听器
 * @author huangkh
 *
 */
final class StartListener implements ServletContextListener, ServletContextAttributeListener {
	
	private Logger logger = LoggerFactory.getLogger(StartListener.class);
	
	private GraphQLModularSchemalBuilder builder;
	private volatile ServerContainer container;

	/**
	 * 
	 */
	public StartListener(GraphQLModularSchemalBuilder builder) {
		this.builder = Objects.requireNonNull(builder, "\"builder\" cannot be null.");
	}
	
	

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		Object value = sce.getServletContext().getAttribute(ServerContainer.class.getName());
		if (value != null) {
			this.startWebSocketEndPoint((ServerContainer)value);
		}
	}



	@Override
	public void attributeAdded(ServletContextAttributeEvent event) {
		if (this.container == null) {
			if (event.getName().equals(ServerContainer.class.getName())) {
				this.startWebSocketEndPoint((ServerContainer)event.getValue());
			}
		}
	}
	
	protected synchronized void startWebSocketEndPoint(ServerContainer container) {
		if (this.container == null) {
			this.container = container;
			
			try {
				container.addEndpoint(
						javax.websocket.server.ServerEndpointConfig.Builder
								.create(GraphQLWebsocketServlet.class, "/subscriptions")
								.configurator(new GraphQLWSEndpointConfigurer(()->this.builder.buildConfiguration()))
								.build()
				);
			}catch(Exception e){
				if (logger.isErrorEnabled()){
					logger.error(e.getMessage(), e);
				}
			}
		}
	}
}
